/*
* $Id: FieldValuesOperation.cpp 152 2010-09-23 18:28:55Z volok-aleksej@yandex.ru $
*
* Copyright 2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "FieldValuesOperation.h"
#include "../Tables/UserFieldsTable.h"
#include "../Tables/FieldValuesTable.h"

CFieldValuesOperation::CFieldValuesOperation(){}
CFieldValuesOperation::~CFieldValuesOperation(){}

CFieldValuesOperation::content::content(){
	Clear();
}
void CFieldValuesOperation::content::Clear(){
	s_nId = 0;
	s_table = TypeField::DEFAULT;
	s_aUserFields.clear();
}

void CFieldValuesOperation::AddValue(IDatabase* pDatabase){
	if(!m_content.s_table)
		return;
	CUserFieldsTable userFieldTable;
	CFieldValuesTable fieldValuesTable;
	if(m_content.s_aUserFields.empty())
		m_content.s_nId = 0;
	else
		m_content.s_nId = fieldValuesTable.GetMaxId(pDatabase) + 1;
	for(std::map<std::tstring, std::tstring>::iterator it = m_content.s_aUserFields.begin(); it != m_content.s_aUserFields.end(); it++){
		fieldValuesTable.m_content.s_strName = it->first;
		fieldValuesTable.m_content.s_strValue = it->second;
		fieldValuesTable.m_content.s_nId = m_content.s_nId;
		userFieldTable.m_content.s_strName = it->first;
		userFieldTable.m_content.s_table = m_content.s_table;
		IResult* pResult = userFieldTable.GetValue(pDatabase);
		if(pResult->GetSizeResult())
 			fieldValuesTable.m_content.s_type = ((CUserFieldsTable::content*)(*pResult)[0])->s_type;
		else
			fieldValuesTable.m_content.s_type = TypeField::STRING;
		pResult->Free();
		fieldValuesTable.SetValue(pDatabase);
	}
}

void CFieldValuesOperation::UpdateValue(IDatabase* pDatabase){
	for(std::map<std::tstring, std::tstring>::iterator it = m_content.s_aUserFields.begin(); it != m_content.s_aUserFields.end(); it++){
		CFieldValuesTable fieldValues;
		if(!m_content.s_nId)
			m_content.s_nId = fieldValues.GetMaxId(pDatabase) + 1;
		fieldValues.m_content.s_strName = it->first;
		fieldValues.m_content.s_nId = m_content.s_nId;
		IResult * pResult = fieldValues.GetValue(pDatabase);
		if(pResult->GetSizeResult()){
			fieldValues.m_content.s_strName = it->first;
			fieldValues.m_content.s_nId = m_content.s_nId;
			fieldValues.m_content.s_strValue = it->second;
			fieldValues.UpdateValue(pDatabase);
		}else{
			fieldValues.m_content.s_strName = it->first;
			fieldValues.m_content.s_nId = m_content.s_nId;
			fieldValues.m_content.s_strValue = it->second;
			CUserFieldsTable userFieldTable;
			userFieldTable.m_content.s_strName = it->first;
			userFieldTable.m_content.s_table = m_content.s_table;
			IResult* pResult1 = userFieldTable.GetValue(pDatabase);
			if(pResult->GetSizeResult())
				fieldValues.m_content.s_type = ((CUserFieldsTable::content*)(*pResult1)[0])->s_type;
			else
				fieldValues.m_content.s_type = TypeField::STRING;
			pResult1->Free();
			fieldValues.SetValue(pDatabase);
		}
		pResult->Free();
	}
}